<?php


namespace App\Services;


use App\Model\Normal;
use App\Model\RefundLog;
use GuzzleHttp\Client;
use Hyperf\Guzzle\CoroutineHandler;
use Hyperf\Guzzle\HandlerStackFactory;
use Hyperf\Utils\ApplicationContext;
use App\Services\icbc\DefaultIcbcClient;
use App\Services\icbc\IcbcConstants;

class BankService
{
    public string $appId = '11000000000000029835';
    private string $priKey  ='MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCqjeescxoBuaxedM4iQjGpC0mpclhSLo32yXLR/ruWY1SQW+KexNJ4jjIuyuasivWVtJCjlGUZHYVnUP/lxVPIMoZA558/W4l94ittiTXvQVJLdX4sQ9lIxI0LibE6qTarOaeaqzAftbccEPUgw9KxrbXmcEg4uCiadibW59wPtYnJdW1JH59XehQyZVtpQweEuqznaAGi7sd95vycupLnz/34Cn988KfPsf8thI+otJvjp3bFcyvEpln6kEza5lgTSUcWWuwWE6pX38yVd8wBEJ68lkcUTXvaFf6EcIzHfk3BcbuYGoUlsQcPWWJVTTq7l9Q8diL9XUdCELmh4CVdAgMBAAECggEAKmtY779A/KTdhjCvBD5Kc6znCUnzRZ1mmbbI5AnjRig2ZCE2YB676lgTiyfT754wLqfWQZkq+/AnueafftpxWB2Y3pO9O9jcfX6/JmM2EufAPBxg4UmOxVZ9bh01A04K1tNkKEfjlD9x530gOqH5yU9XKpVKoTDMiH5ScqkARreMOEx5Agk4I8A+yzb+OWvCKra3N8cjVUb/FkuZhOEpRHCmL0ckeV3GbRDcrG828zvuMInkdWMilrx5cZYwvFRpVvKBGzbnnB0wCtqsdYFK5R0vUOsb1ARVLZ4L2ngHMUnNDjv65lNEnNxrVZbyhM8o7Ryxy+fq4jo1h2Akme7GgQKBgQDR6rvU9w6UqJNeFdgXb1y/XTVEj9fErUBHILGTZwvOharsY5S5Hf8ZtL5CS5tu/glIo0UK20/i6dAE1jrIdNduy5/v548i2tXGrLzB6mkp2u/KHJC+wI4h/Hi9YHhDwK5bndWbMpqgWNhBZHblZ7DGxFS7+hKs66hOlyQUfebtxQKBgQDP/wExEIIWWlYuPF/iqIOIMa83fXiRcumMZ9igK+c14LOCCFiRBuT+cwozaEnyM+Pn0YCPe7P217X59GgTd8GNETJ69uJbjzjshpg3NMxpolOFb6xgUr1igScADHnsiCW5WO33Rk5H7nC8Vpq+VGyuUsS2wAF6TrCj9We2wswquQKBgHFUX3AMqeyMTnN/K5kLYHFYKwgG+KCQQKGl/vjrqy4mcC8LXCHNFgqU0BsOoq37rJtwujewS6LgRJQ37KiInD6O5Jwq0dYpezy1yXqPyZL1RnxBi8vQPWwP2Ee1q3g4sGl5/va5DU4AaVB0otQbdQ76tByAWFDPMaCsbKg7iM9ZAoGBAMTBOjRapGRWwk1siVvVAs/UCCbaxzH33RwXpCEoRsh9rfFkybsvJXHaCx1EGydFlOLXGOEiKMRpm9g+LjG0SGCUkwclAk2Qd02vqNAYXwHSL2X7lLltq39CI011f+STifQCPuF6HVUIJpbS6gD/xetFmpYxnXRAefIvlBObxBzpAoGBAKJABPWq5Gnx1HrDUO3RvPt5sxusZwNyDw8u/XGyDc94F2DLGeOYBne0QWHhX+S5RyL70qV4RK8Sn6Utc5qWRASWtBw8nm3b//gH9MDt2JcdUEwkMAyhIsoWvLMf3BKAdluByCJ8/NQb7J+EIT1HZXRbvfHRDImRirWw/T6rHG90';
    private string $pubKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMpjaWjngB4E3ATh+G1DVAmQnIpiPEFAEDqRfNGAVvvH35yDetqewKi0l7OEceTMN1C6NPym3zStvSoQayjYV+eIcZERkx31KhtFu9clZKgRTyPjdKMIth/wBtPKjL/5+PYalLdomM4ONthrPgnkN4x4R0+D4+EBpXo8gNiAFsNwIDAQAB';
    public string $mer_id = '120811990060';
    public string $aesKey = '5ZWzxn8hBBuUDJSUzjVZBA==';
    public string $uri = 'https://gw.open.icbc.com.cn/api/cardbusiness/aggregatepay/b2c/online/consumepurchase/V1';
    public function __construct(){

    }

    public function createOrder($data){
        $date = new \DateTime();
        $formattedDate = $date->format('Y-m-d\TH:i:s');
        $biz_content =array(
            "mer_id"=>$this->mer_id,
            "mer_prtcl_no"=>$this->mer_id,
            "pay_mode"=>$data['pay_mode'],
            "access_type"=>"9",
            "out_trade_no"=>$data['number'],
            "decive_info"=>$data['device_info'],
            "body"=>$data['body'],
            "fee_type"=>"001",
            "icbc_appid"=>$this->appId,
            "mer_url"=>$data['notify_url'],
            "orig_date_time"=>$formattedDate,
            "spbill_create_ip"=>$data['ip'],
            "total_fee"=>$data['total_fee'].'',
            "notify_type"=>"HS",
//                'union_id' =>'2088002005484520',
//                'open_id'=>'on3Ny6-rS046xQ4FnZPzWsLvUiXM',
//                'shop_appid'=>'wxefaaba48e16c9073'
        );
        if($data['pay_mode'] == '10'){
            $biz_content['union_id'] = $data['open_id'];
        }else{
            $biz_content['open_id'] = $data['open_id'];
            $biz_content['shop_appid'] = 'wxefaaba48e16c9073';
        }
        $request = array(
            "serviceUrl" => $this->uri,
            "method" => 'POST',
            "isNeedEncrypt" => false,
            "biz_content" =>$biz_content
        );
        //以下构造函数第1个参数为appid，第2个参数为RSA密钥对中私钥，第6个参数为API平台网关公钥
        $client = new DefaultIcbcClient(
            $this->appId,
            $this->priKey,
            IcbcConstants::$SIGN_TYPE_RSA2,
            '',
            '',
            $this->pubKey,
            '',
            '',
            '',
            '');
        $resp = $client->execute($request,uniqid(),'');//执行调用;msgId消息通讯唯一编号，要求每次调用独立生成，APP级唯一
        $respObj = json_decode($resp,true);
//        echo '\\n';
//        if($respObj["return_code"] == 0){ //sucess
//            echo $respObj["return_msg"];
//        }else{//fail
//            echo $respObj["return_msg"];
//        }
        return $respObj;
    }

    /**检查订单状态
     * @param $order
     * @return void
     */
    public function queryStatus($order,$type ='0'){
        $request = array(
            "serviceUrl" => 'https://gw.open.icbc.com.cn/api/cardbusiness/aggregatepay/b2c/online/orderqry/V1',
            "method" => 'POST',
            "isNeedEncrypt" => false,
            "biz_content" => array(
                "mer_id"=>$this->mer_id,
                "out_trade_no"=>$order->number,
                "order_id"=>$order->out_ord_id,
                "deal_flag"=>$type,
                "icbc_appid"=>$this->appId
            )
        );
        $client = new DefaultIcbcClient($this->appId,
            $this->priKey,
            IcbcConstants::$SIGN_TYPE_RSA2,
            '',
            '',
            $this->pubKey,
            '',
            '',
            '',
            '');
        $resp = $client->execute($request,uniqid(),'');//执行调用;msgId消息通讯唯一编号，要求每次调用独立生成，APP级唯一
        $respObj = json_decode($resp,true);
        return $respObj;
    }

    /**退款
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    public function refund($data){
        $request = array(
            "serviceUrl" => 'https://gw.open.icbc.com.cn/api/cardbusiness/aggregatepay/b2c/online/merrefund/V1',
            "method" => 'POST',
            "isNeedEncrypt" => false,
            "biz_content" => array(
                "mer_id"=>$this->mer_id, //商户编号
                "outtrx_serial_no"=>$data['refund_no'], //外部退货流水号
                "order_id"=>$data['order_id'], //消费工行订单号
                "out_trade_no"=>"", //外部订单号
                "ret_total_amt"=>''.$data['fee']*100, //退货总金额
                "trnsc_ccy"=>"1", //交易币种
                "icbc_appid"=>$this->appId, //商户在工行API平台的APPID
            )
        );
        $save['refund_no'] = $data['refund_no'];
        $save['number'] = $data['number'];
        $save['type'] = $data['type'];
        $save['reject_amt'] = ''.$data['fee']*100;

        $client = new DefaultIcbcClient($this->appId,
            $this->priKey,
            IcbcConstants::$SIGN_TYPE_RSA2,
            '',
            '',
            $this->pubKey,
            '',
            '',
            '',
            '');
        $resp = $client->execute($request,uniqid(),'');//执行调用;msgId消息通讯唯一编号，要求每次调用独立生成，APP级唯一
        $respObj = json_decode($resp,true);
        if($respObj['return_code'] == 0){
            $save['status'] = 1;
            $save['refund_time'] = $respObj['refund_time'];
        }else{
            $save['status'] = 2;
        }
        RefundLog::create($save);
        return $respObj;
    }

    /**查询退款状态
     * @return mixed
     * @throws \Exception
     */
    public function queryRefund($data){
        $request = array(
            "serviceUrl" => 'https://gw.open.icbc.com.cn/api/mybank/pay/qrcode/scanned/returnstatus/V3',
            "method" => 'POST',
            "isNeedEncrypt" => false,
            "biz_content" => array(
                "mer_id"=>$this->mer_id,
                "cust_id"=>$data['openid'],
                "out_trade_no"=>$data['number'],
                "reject_no"=>$data['refund_no'],
                "reject_amt"=>$data['fee']*100,
            )
        );
        $client = new DefaultIcbcClient($this->appId,
            $this->priKey,
            IcbcConstants::$SIGN_TYPE_RSA2,
            '',
            '',
            $this->pubKey,
            '',
            '',
            '',
            '');

        $resp = $client->execute($request,uniqid(),'');//执行调用;msgId消息通讯唯一编号，要求每次调用独立生成，APP级唯一
        $respObj = json_decode($resp,true);
        return $respObj;
    }

    public function curlPost($url, $data,$type = 'json')
    {
        $container = ApplicationContext::getContainer();
        $handlerStackFactory = $container->get(HandlerStackFactory::class);
        $handlerStack = $handlerStackFactory->create();
        $client = new Client(['handler' => new CoroutineHandler($handlerStack)]);

        $response = $client->post($url, [
            'headers' => [
                'Content-Type' => 'application/json',
            ],
            $type => $data
        ]);

        return $response->getBody()->getContents();
    }

}
